import { observable, action, toJS } from 'mobx';
import * as Bctt from "../../constants/BaseListConstant";
import { message, Button, Modal } from "antd";
import * as Apis from "../../apis/Api";

import _ from 'lodash';
import { WeaTableNew, WeaForm } from 'comsMobx';
const { TableStore } = WeaTableNew;


class CommonLedgerStore {

    constructor(props){
        
    }

    @observable loading = false;
    @observable viewTop = true;
    @observable iconBgcolor = "";
    @observable topInfo = { "titleName": "", "titleIcon": "", "iconBgcolor": "" };//头部信息
    @observable rightMenu = [];
    @observable rightMenuFromCube = [];//建模的右键
    @observable rightMenuFromCustom = [];//自定义的右键
    @observable showSearchAd = false;
    @observable searchKey = "";
    @observable searchConditionForm = new WeaForm();
    @observable searchConditionComponents = {};
    @observable tableStore = new TableStore();
    @observable routerParams = {};
    @observable cubeParams = {};
    @observable searchInputName = Bctt.TAB_SEARCH_INPUT_NAME;
    @observable contractType = [];
    @observable rpData = [];//普通台账报表头
    @observable riskRpData = [];//风险台账报表头
    @observable commonParams = {};//用来存储dataKey,formId,customid,guid等
    @observable synergyParams = { isUse: false, isShow: false, refId: -1, tabKey: "0" };
    @observable shareStore = {};
    @observable searchBaseParams = {};
    @observable dialog = {visible:false};
    @observable Card = {};

    @action
    componentWillMount = (componentParams) => {
        this.routerParams = componentParams;
        this.searchConditionForm = new WeaForm();
        this.tableStore = new TableStore();
        this.getContractType();
        this.clearSynergy();
    }

    // @action
    // getCubeParams = () =>{
    //     Apis.getModeInfo({}).then(data => {
    //         this.cubeParams = data[this.routerParams.page];
    //     });

        
        //举例数据
        // const p = [{page:"con_add",customId:1222,layoutid:1122},{page:'mine',customid:'1042'},{page:'payplan',customid:'1061'},{page:'charge',customid:'1058'},{page:'expend',customid:'1043'},{page:'income',customid:'1060'},{page:'ticket',customid:'1046'}];
        // for(let i=0; i<p.length; i++){
        //     if(p[i].page == this.routerParams.page){
        //         this.cubeParams= p[i];
        //         break;
        //     };
        // }
    // }

    @action
    componentDidMount = () => {
        // const weaCube = window.weaCube;
        this.shareStore = new weaCube.common.ShareStore();
        this.Card = new weaCube.common.CardStore();
        this.loading = true;
        Apis.getModeInfo({}).then(data => {
            this.cubeParams = data[this.routerParams.page];
            this.searchInputName = data[this.routerParams.page].cons_name;
            let requestParams = {...this.cubeParams,...this.routerParams};
            this.getInitInfoFromCube(requestParams, this.initInfoComponentInitCallBack);
            this.getTableData(requestParams, this.tableComponentInitCallBack);
            if("risk"==this.routerParams.page){
                this.getRpData(requestParams, this.rpComponentInitCallBack1);
            }else{
                this.getRpData(requestParams, this.rpComponentInitCallBack);
            }
            
            this.getRightMenuFromCustom(requestParams, this.rightMenuFromCustomComponentInitCallBack);
            this.getConditionFromCube(requestParams, this.conditionComponentInitCallBack);
        });

    }

    @action
    componentWillUnmount = () => {
        this.loading = false;
        this.viewTop = true;
        this.iconBgcolor = "";
        this.topInfo = { "titleName": "", "titleIcon": "", "iconBgcolor": "" };//头部信息
        this.rightMenu = [];
        this.rightMenuFromCube = [];//建模的右键
        this.rightMenuFromCustom = [];//自定义的右键
        this.showSearchAd = false;
        this.searchKey = "";
        this.searchConditionForm = new WeaForm();
        this.searchConditionComponents = {};
        this.tableStore = new TableStore();
        this.routerParams = {};
        this.cubeParams = {};
        this.searchInputName = Bctt.TAB_SEARCH_INPUT_NAME;
        this.contractType = [];
        this.rpData = [];//普通台账报表头
        this.riskRpData = [];//风险台账报表头
        this.commonParams = {};//用来存储dataKey,formId,customid,guid等
        this.synergyParams = { isUse: false, isShow: false, refId: -1, tabKey: "0" };
        this.shareStore = {};
        this.searchBaseParams = {};
        this.dialog = {visible:false};
        this.Card = {};

        // this.loading = false;
        // this.viewTop = true;
        // this.rightMenu = [];
        // this.showSearchAd = false;
        // this.searchKey = "";
        // this.tableStore = {};
        // this.routerParams = {};
        // this.searchConditionForm = {};
        // this.searchConditionComponents = {};
        // this.rpData = [];
        // this.riskRpData = [];
        window._cubeCard={};
    }

    /**获取合同类型树 */
    @action
    getContractType(requestParams = {}) {
        Apis.getContractType().then(data => {
            this.contractType = [{
                childs: data.datas,
                domid: "0-0",
                haschild: true,
                isopen: true,
                key: "0-0",
                name: '全部',
              }]
            //this.contractType = data.datas;
        });
    }

    /**获取合同列表信息 */
    getTableData(requestParams, callBackFn) {

    }

    /**获取合同列表信息的回调 */
    @action
    tableComponentInitCallBack = (data = {}) => {
        this.clearSynergy();
        this.bindAction();
        this.commonParams.dataKey = data.datas;
        this.tableStore.getDatas(data.datas, 1);
        this.loading = false;
    }

    /**获取高级搜索条件 */
    getConditionFromCube(requestParams, callBackFn) {

    }

    /**获取高级搜索条件的回调 */
    @action
    conditionComponentInitCallBack = (data = {}) => {
        this.searchConditionComponents = data.conditionInfo;
        this.searchConditionForm.initFormFields(data.conditionInfo);
    }

    /**获取建模右键和头部信息 */
    getInitInfoFromCube(requestParams, callBackFn) {

    }

    /**获取建模右键和头部信息的回调 */
    @action
    initInfoComponentInitCallBack = (data = {}) => {
        this.topInfo = { titleName: data.top.name, titleIcon: data.top.icon, iconBgcolor: data.top.iconBgcolor };
        this.rightMenuFromCube = data.rightMenus;

        this.commonParams.customId = data.customId;
        this.commonParams.formId = data.formId;
        this.commonParams.modeId = data.modeId;
    }

    /**获取自定义的右键 */
    getRightMenuFromCustom(requestParams, callBackFn) {

    }

    /**获取自定义的右键的回调 */
    @action
    rightMenuFromCustomComponentInitCallBack = (data = {}) => {
        this.rightMenuFromCustom = data.datas;
    }

    /**获取合同列表顶部统计信息 */
    getRpData(requestParams, callBackFn) {

    }

    /**获取合同列表顶部统计信息的回调 */
    @action
    rpComponentInitCallBack = (data = {}) => {
        this.rpData = data.datas;
        this.riskRpData = [];
    }

    @action
    rpComponentInitCallBack1 = (data = {}) => {
        this.riskRpData = data.datas;
        this.rpData = [];
    }

    /**显示协同区 */
    @action
    showSynergy = (bool = false, refId, tabKey, title) => {
        this.synergyParams.isUse = bool;
        this.synergyParams.isShow = bool;
        this.synergyParams.refId = refId;
        this.synergyParams.tabKey = tabKey;
        this.synergyParams.title = title;
    }

    /**清除协同区 */
    @action
    clearSynergy() {
        this.synergyParams.isUse = false;
        this.synergyParams.isShow = false;
    }

    
    reLoad = () => {
        this.tableStore.getDatas(this.tableStore.dataKey, this.tableStore.current, this.tableStore.pageSize, this.tableStore.sortParams);
    }

    @action
    doSearch = (params = {}) => {
        let that = this;
        this.loading = true;
        this.setShowSearchAd(false);
        let initParams = {};
        initParams[this.searchInputName] = this.searchKey;
        const searchParamsAd = this.searchConditionForm.getFormParams();
        let requestParams = { ...initParams, ...searchParamsAd, ...params, ...this.cubeParams, ...this.routerParams };
        for (let item in requestParams) {
            if (requestParams[item] == ""||(item==="typeTreeId"&&requestParams["typeTreeId"]=="0-0")) {
                delete requestParams[item];
                delete that.searchBaseParams[item];
            }

        }
        this.searchBaseParams = {...this.searchBaseParams,...requestParams};
        this.getTableData(this.searchBaseParams, this.doSearchCallBack);
        if("risk"==this.routerParams.page){
            this.getRpData(this.searchBaseParams, this.rpComponentInitCallBack1);
        }else{
            this.getRpData(this.searchBaseParams, this.rpComponentInitCallBack);
        }
        
    }

    @action
    doSearchCallBack=(data = {})=>{
        this.clearSynergy();
        this.tableStore.getDatas(data.datas, 1);
        this.loading = false;
    }

    @action
    reload = () => {
        this.tableStore.getDatas('', this.tableStore.current, this.tableStore.pageSize)
    }

    getListKey=(data)=> {
        if ('randomFieldSubKeyd_id' in data) {
            return `${data.randomFieldId}_${data.randomFieldSubKeyd_id}`;
        } else {
            return `${data.randomFieldId}`;
        }
    }

    /**列表选中id抛到全局 */
    bindAction = () => {
        window._xtable_CheckedCheckboxId = () => {
            this.tableStore.datas.map(d => this.tableStore.selectedRowKeys.indexOf(this.getListKey(d)) > -1).map(d => d.randomFieldId);
            return _.uniq(this.tableStore.selectedRowKeys.map(d => d.split('_')[0])).join(',');
        }
    }
    
    /**检查列表选中状态 */
    checkSeleted = () => {
        const selectedRows = window._xtable_CheckedCheckboxId();
        if (selectedRows.length < 1) {
            message.error('请至少选择一条记录。');
            return false;
        }
        return true;
    }

    @action
    closeDialog = () => {
        //window.open('/spa/cube/index.html#/main/cube/card?type=1&modeId=' + this.commonParams.modeId + '&formId=' + this.commonParams.formId);
        // window.openFullWindowHaveBar('/spa/contract/index.html#/main/contract/bills/create');
        this.dialog.visible = false;
        this.dialog.url = '';
    }

    showCardCallBack=(billid)=>{
        message.success('保存成功');
        
        if(billid){
            this.closeDialog();
        }else{
            this.doAdd();
        }
        this.reload();
        return null;
    }

    @action
    doAdd = () => {
        //window.open('/spa/cube/index.html#/main/cube/card?type=1&modeId=' + this.commonParams.modeId + '&formId=' + this.commonParams.formId);
        // window.openFullWindowHaveBar('/spa/contract/index.html#/main/contract/bills/create');
        // this.dialog.url = '#/main/contract/bills/create';
        const p =  this.routerParams;
        if(p&&(p.page=="ticket"||p.page=="incom"||p.page=="pay")){
            window._cubeCard={
                reLoad:this.showCardCallBack
            }
            this.dialog.visible = true;
            this.Card.init({type:1,modeId:this.commonParams.modeId,formId:this.commonParams.formId,customid:this.commonParams.customId});
            this.Card.modeExcel.containerWidth = 1000;
        }else{
            window.openFullWindowHaveBar('/spa/contract/index.html#/main/contract/bills/create');
        }
    }

    @action
    doDel = () => {
        if (!this.checkSeleted()) {
            return;
        }
        let params = { customid: this.commonParams.customId, billids: window._xtable_CheckedCheckboxId(),operate: 'DeleteAction', };
        this.deleteData(
            params,
            ({ message }) => {
                Modal.success({
                    content: message,
                });
                this.reload();
            }
        );
    }

    @action
    doBatchImport = () => {
        window.open(`/spa/cube/engine.html#/cubeengine/app/modebatchimport?modeid=${this.commonParams.modeId}`);
    }

    @action
    doBatchShare = () => {
        if (!this.checkSeleted()) {
            return;
        }
        this.shareStore.batchShare(this);
    }

    @action
    doExcelOut = () => {
        window.location.href = `/weaver/weaver.formmode.excel.ExpExcelServer?showOrder=all&iscustomsearch=1&comefrom=frommode&modeCustomid=${this.commonParams.customId}&dataKey=${this.commonParams.dataKey}`;
    }

    @action
    doBatchEdit = () => {
        if (!this.checkSeleted()) {
            return;
        }
    }
    
    @action 
    deleteData = (params={}, callback) => {
        Apis.deleteData(params).then(({ status, error, ...data }) => {
            if (status == '1') {
                callback(data);
            } else {
                message.error(error)
                throw error;
            }
        })
    }
    
    /**获取右键菜单 */
    getRightMenus() {
        let { rightMenuFromCube, rightMenuFromCustom } = this;
        let btnArr = [];

        rightMenuFromCube.map(c => {
            
            let menus = {
                icon: <i className={c.icon} />,
                content: c.name,
                key: c.key,
                onClick: key => {
                    this.rightMenuClick(c.function);
                }
            };
            //过滤下列表不支持的右键
            if(c.function=="submitData"||c.function=="Add"||c.function=="Del"||c.function=="BatchImport"||c.function=="batchShare")
            btnArr.push(menus);
        });

        rightMenuFromCustom.map(c => {
            let menus = {
                icon: <i className={c.menuIcon} />,
                content: c.menuName,
                key: c.type,
                onClick: key => {
                    this.rightMenuClick(key);
                }
            };
            btnArr.push(menus);
        });

        return btnArr;
    }

    /**获取顶部菜单 */
    getTopButtons() {
        const { rightMenuFromCube, rightMenuFromCustom, rightMenu } = this;
        let btnArr = [];
        rightMenuFromCube && rightMenuFromCube.length > 0 && rightMenuFromCube.map(m => {
            m.quickButton && btnArr.length < 4 && btnArr.push(
                <Button type="primary"
                    disabled={false}
                    onClick={() => {
                        this.rightMenuClick(m.function);
                    }}>
                    {m.name}
                </Button>
            );
        });

        rightMenuFromCustom && rightMenuFromCustom.length > 0 && rightMenuFromCustom.map(m => {
            m.isTop == "1" && btnArr.length < 4 && btnArr.push(
                <Button type="primary"
                    disabled={m.isControl == '1' && toJS(tableStore.selectedRowKeys).length == 0}
                    onClick={() => {
                        this.rightMenuClick(m.type);
                    }}>
                    {m.menuName}
                </Button>
            );
        });
        let btnArrCustom = this.getTopButtonsCustom();
        return btnArrCustom.concat(btnArr);
    }

    getTopButtonsCustom() {
        let btnArr = [];
        return btnArr;
    }

    /**菜单点击执行函数 */
    rightMenuClick(key) {
        if (key == Bctt.CUBE_FUN_SUBMITDATA) {
            this.doSearch();
        } else if (key == Bctt.CUBE_FUN_ADD) {
            this.doAdd();
        } else if (key == Bctt.CUBE_FUN_DEL) {
            this.doDel();
        } else if (key == Bctt.CUBE_FUN_BATCHIMPORT) {
            this.doBatchImport();
        } else if (key == Bctt.CUBE_FUN_BATCHSHARE) {
            this.doBatchShare();
        } else if (key == Bctt.CUBE_FUN_GETALLEXCELOUT) {
            this.doExcelOut();
        } else if (key == Bctt.CUBE_FUN_DOBATCHEDIT) {
            this.doBatchEdit();
        } else if (key == Bctt.BTN_SEARCH) {
            this.doSearch();
        } else if (key == Bctt.BTN_COLUMN) {
            this.tableStore.setColSetVisible(true);
            this.tableStore.tableColSet(true);
        }
    }

    excelExportCallBack(data) {
        window.location = Bctt.ADDR_EXCEL_EXPORT;
    }

    @action
    setShowSearchAd = (bool = false) => {
        this.showSearchAd = bool;
    }

    @action
    setSearchKey = (v = "") => {
        this.searchKey = v;
        try {
            let searchKeyField = {};
            searchKeyField[this.searchInputName] = { value: v };
            this.searchConditionForm.updateFields(searchKeyField, false);
        } catch (error) {
            // 高级搜索中没有searchKey的情况
        }
    }

    @action
    searchConditionFieldChange = (fieldObj) => {
        if (fieldObj[this.searchInputName]) {
            this.searchKey = fieldObj[this.searchInputName].value;
        }
    }

    clearAdFields = () => {
        this.searchConditionForm.reset();
        this.searchKey = "";
    }

    excelExport(excelExportCallBack) {

    }

}

export default CommonLedgerStore;